package org.example;

import org.example.model.TableLineage;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JdbcFinkConnectorOptionParser implements FinkConnectorOptionParser {

    Pattern pattern = Pattern.compile("jdbc:(\\w+):\\/\\/([\\w\\.]+):(\\d+)\\/([\\w\\d]+)(\\?.*)?");

    @Override
    public String getTableName(TableLineage tableLineage) {
        return tableLineage.getOptions().get("table-name");
    }

    @Override
    public String getDatabaseName(TableLineage tableLineage) {
        String url =  tableLineage.getOptions().get("url");
        Matcher matcher = pattern.matcher(url);

        if (matcher.find()) {
            String dbType = matcher.group(1);
            String host = matcher.group(2);
            String port = matcher.group(3);
            String database = matcher.group(4);
            String parameters = matcher.group(5);
            return database;
        }else {
            throw new
                    RuntimeException("Invalid JDBC URL");
        }

    }

    @Override
    public String getDataBaseType(TableLineage tableLineage) {
        String url =  tableLineage.getOptions().get("url");
        Matcher matcher = pattern.matcher(url);

        if (matcher.find()) {
            String dbType = matcher.group(1);
            return dbType;
        }else {
            throw new
                    RuntimeException("Invalid JDBC URL");
        }
    }
}
